﻿using System;
using System.Net;
using System.Net.Sockets.Kcp;

namespace PENet
{
    public enum SessionState 
    {
   None,
   Connected,
        DisConnected
    }

    public abstract class KCPSession
    {
        protected uint m_sid;
        Action<byte[], IPEndPoint> m_udpSender;
        protected IPEndPoint m_remotePoint;
        protected SessionState m_sessionState=SessionState.None;
        public Action<uint> OnSessionClose;

        public KCPHandler m_handle;
        public Kcp m_kcp;

        public void InitSession(uint sid,Action<byte[],IPEndPoint>udpSender,IPEndPoint remotePoint)
        {
            m_sid = sid;
            m_udpSender = udpSender;
            m_remotePoint = remotePoint;
            m_sessionState = SessionState.Connected;

            m_handle = new KCPHandler();
            m_kcp = new Kcp(sid, m_handle);
            m_kcp.NoDelay(1, 10, 2, 1);
            m_kcp.WndSize(64, 64);
            m_kcp.SetMtu(512);

            m_handle.Out=(Memory<byte>buffer)=> 
            {
                byte[] bytes = buffer.ToArray();
                m_udpSender(bytes,m_remotePoint);
            };
        }

        public void CloseSession()
        {
            OnDisConnected();
            OnSessionClose?.Invoke(m_sid);
            OnSessionClose = null;
            m_sessionState = SessionState.DisConnected;
            m_remotePoint = null;
            m_udpSender = null;
            m_sid = 0;
            m_handle = null;
            m_kcp = null;
        
        }

        protected abstract void OnDisConnected();

        public bool IsConnected()
        {

            return m_sessionState == SessionState.Connected;
        }
    
    
    }
}
